var React = require('react-native');
import {styles,colors,fontSize,Icon,size} from './Css';
var {width,height} = size;

import MModal  from './MModal';
import RootSiblings  from './RootSiblings';
import Main from './Main';
import Config from '../common/Config';


var {
    TouchableOpacity,
    Image,
    Text,
    View,
    Component,
    WebView,
    AsyncStorage,
    TextInput
    } = React;


/**
 * modal left
 */
class ModalLeft extends Component{

    constructor() {
        super(...arguments);
        this.state = {
            pic:'http://wx.wefi.com.cn/images/bulr/Blur_02.jpg',

            userinfo:{
                email:'登陆'
            }
        };
    }
    goRouter(router,params){
        Main.goRouter(this,router,params);
        RootSiblings.hideAll();
    }
    componentDidMount(){
        var userinfo =Main.getUserinfo(this);
        if(userinfo)
            this.setState({
                userinfo:userinfo
            });

    }
    loginBtn(){

        if(this.state.userinfo.id)
              this.goRouter('UserCenter');
        else
              this.goRouter('Login');

    }
    logout(){
        AsyncStorage.setItem('_user','',(err)=>{

            if(err!=null)
                return;
            this.setState({
                userinfo:{email:'登录'}
            });
        });
    }
    render (){
        var userinfo = this.state.userinfo;
        return(
            <View>
                <View style={[styles.modalTop,styles.itemCenter]}>
                    <Image style={[styles.modalImage]} source={{uri:this.state.pic}}></Image>
                    <TouchableOpacity onPress={()=>{this.loginBtn()}}>
                        <Text style={[styles.modalText,styles.paddingVertical]}>{this.state.userinfo.email}</Text>
                    </TouchableOpacity>
                    {this.state.userinfo.id?
                        <TouchableOpacity onPress={()=>{this.logout()}}>
                            <Text style={[styles.modalText,styles.paddingVertical]}>退出</Text>
                        </TouchableOpacity>
                        :null}
                </View>
                <View style={[styles.modalCenter,styles.borderBottom,styles.fRow]}>
                    <View style={[styles.UViconBox,styles.fRow,styles.UVborderMR]}>
                        <Icon name='ios-chatboxes-outline' size={22} color='#333'/>
                        <TouchableOpacity onPress={()=>{this.loginBtn()}}>
                        <Text style={[styles.modalTextIcon]}> 我的收藏</Text>
                        </TouchableOpacity>
                    </View>

                    <View style={[styles.UViconBox,styles.fRow]}>
                        <Icon name='ios-cloud-download' size={22} color='#333'/>
                        <TouchableOpacity onPress={()=>{this.loginBtn()}}>

                            <Text style={[styles.modalTextIcon]}> 观看记录</Text>
                        </TouchableOpacity>
                    </View>
                </View>
                <View style={[styles.modalDown]}>
                    <View style={[styles.heightQ]}><Text style={[styles.modalTextDown]}>版本:v 1.0.2</Text></View>
                    <View style={[styles.heightQ]}><Text style={[styles.modalTextDown]}>作者:lucifer.p/YiHang</Text></View>
                    <TouchableOpacity style={[styles.heightQ]}
                                      onPress={()=>{this.goRouter('Web',{url:'http://git.oschina.net/man0sions/DotaVideo'})}}>
                        <Text style={[styles.modalTextDown]}>意见反馈</Text>
                    </TouchableOpacity>
                </View>
            </View>
        );
    }
}
/**
 * 用户登录
 */
const Login = React.createClass({
    getInitialState:function(){
        return {
            email:'',
            passwd:'',
            passwd2:'',
            loading:false,
            register:false,

        }
    },
    componentDidMount:function(){
        var userinfo =Main.getUserinfo(this);
        if(userinfo)
            this.setState({
                userinfo:userinfo
            });

    },
    handleSubmit:function(){
        var err = [];
        var method = 'login';
        if(!Main.isEmail(this.state.email))
        {
            err.push("请输入正确的邮箱");
        }
        if(this.state.passwd.length<6)
        {
            err.push("密码必须大于6位");
        }
        if(this.state.register)
        {
            method = 'register';

            if(this.state.passwd2 !=this.state.passwd)
                err.push("两次密码必须一致");
        }
        if(err.length)
        {
         return Main.toast(err.join("\n"),'TOP');
        }
        else


        {
            Main.fetch({
                url:Config.host+'?r=users/'+method,
                method: 'POST',
                body: 'email='+this.state.email+'&password='+this.state.passwd
            },(res)=>{
                var json = res;
                var data = json.data || {};
                console.log(data);
                if(data.id)
                {

                    AsyncStorage.setItem('_user',JSON.stringify(data),function(err){
                        if(!err)
                        {
                            Main.toast("登录成功",'TOP');
                            this.props.app.setState({
                                userinfo:data
                            });
                            this.props.navigator.jumpBack();

                        }
                    }.bind(this));
                }
                else
                {
                    var status = json.status;

                    var msg = status.errorinfo.join("\n") || "邮箱或密码错误";
                    Main.toast(msg,'TOP');

                }
            });

        }

    },
    setTitle:function(){
        this.setState({
            register:!this.state.register
        })
        if(this.state.register)
            this.props.parent.setState({
                title:'注册'
            });
        else
            this.props.parent.setState({
                title:'登录'
            });
    },
    render:function(){
        return (

            <View style={[styles.modalDown]}>
                <View style={styles.inputContainer}>
                    <TextInput
                        placeholder={"邮箱"}
                        keyboardType={'email-address'}
                        autoCapitalize={"none"}
                        autoCorrect={false}
                        returnKeyType={'next'}
                        onSubmitEditing={() => this.refs.pwField.focus()}
                        style={styles.input}
                        onChangeText={(text) => this.setState({email: text})}
                    />
                </View>

                <View style={styles.inputContainer}>
                    <TextInput
                        ref="pwField"
                        placeholder={"请输入密码"}
                        password={true}
                        returnKeyType={'next'}
                        onSubmitEditing={this.handleSubmit}
                        style={styles.input}
                        onChangeText={(text) => this.setState({passwd: text})}
                    />
                </View>
                {this.state.register?
                    <View style={styles.inputContainer}>
                        <TextInput
                            ref="pwField2"
                            placeholder={"再次输入密码"}
                            password={true}
                            returnKeyType={'done'}
                            onSubmitEditing={this.handleSubmit}
                            style={styles.input}
                            onChangeText={(text) => this.setState({passwd2: text})}
                        />
                    </View>
                :null}
                <TouchableOpacity style={styles.button} onPress={this.handleSubmit}>
                    <Text style={styles.buttonText}>{this.state.register?'注册':'登录'}</Text>
                </TouchableOpacity>

                {this.state.loading?<Loading size={20} text={'加载中'}/>:null}
                <View  style={styles.itemRight} >
                    <TouchableOpacity onPress={()=>{this.setTitle()}}>

                        <Text style={[{margin:10,fontSize:fontSize.small,color:colors.danger}]}>
                            {this.state.register?'我有有账号':'我没有账户? 创建'}
                        </Text>
                    </TouchableOpacity>
                </View>
            </View>
        );
    }
});
/**
 * Topav
 */
const Topav = React.createClass({
    getInitialState:function(){
        return{active:7}
    },
    _setTop(day){
       Main.goRouter(this,'TopList',{day:day});
    },
    _renderItem(){
        var items = [
            {label:7,text:'周排行'},
            {label:31,text:'月排行'},
            {label:93,text:'季排行'},
        ];
        return items.map(function (item, key) {
            var active = {};
            if(this.props.active==item.label)
                 active = styles.sortActive;
            return (
                <TouchableOpacity style={[styles.sortitems,active]} onPress={()=>{this._setTop(item.label)}} key={key}>
                    <Text style={[styles.sortTitle]}>{item.text}</Text>
                </TouchableOpacity>
            );
        }.bind(this));
    },
    render(){
        return (
            <View style={styles.sortContainer}>
                {this._renderItem()}
            </View>
        );
    }
})
/**
 * 全局header
 * 用法  : <Header />
 * @param
 */

const Header = React.createClass({
    getInitialState: function () {
        return {
            title: '每日精选',
            modalShow:false,
        }
    },
    _showModal:function(){
        var show = !this.state.modalShow;
        this.setState({
            modalShow:show,
        });
        var modal = (<MModal visible={show} >
            <ModalLeft {...this.props}></ModalLeft>
        </MModal>);

        if(show)
            RootSiblings.show(modal);

        else
            RootSiblings.hideAll(modal);


    },
    _renderMenu: function () {
        var icon = 'android-menu';
        if (this.state.modalShow)
            icon = 'chevron-down';
        return (
            <TouchableOpacity
                style={[styles.items3,styles.itemLeft,styles.paddingHorizontalA]}
                onPress={()=>{this._showModal()}}
            >
                <Icon name={icon} size={23} color='#000'/>
            </TouchableOpacity>
        );

    },

    render: function () {
        var title = this.props.title || this.state.title;
        return (
            <View>
                <View style={[styles.header,styles.bgColor]}>
                    {this._renderMenu()}

                    <View style={[styles.items3,styles.itemCenter]}>
                        <Text style={[styles.headtitle]}>{title}</Text>
                    </View>
                    <TouchableOpacity style={[styles.items3,styles.itemRight,styles.paddingHorizontalA]}
                                      onPress={()=>{Main.goRouter(this,'Search')}}
                    >
                        <Icon name='ios-search' size={20} color='#000'/>
                    </TouchableOpacity>
                </View>
            </View>
        );
    }
});


/**
 * Footer
 * 用法  : <Footer />
 * @param
 */


const Footer = React.createClass({
    getInitialState: function () {
        return {}
    }
    ,
    _renderText: function (name, router) {
        var textCss = {};
        if (this.props.active == router) {
            textCss = {color: colors.success,fontWeight: 'bold'};
        }


        return <Text style={[styles.footerItemsFont,textCss]}>{name}</Text>;

    },
    _renderItem(){

        return Config.routers.map(function (item, key) {


            var center = key == 1 ? styles.footerItemsCenter : {};
            var params = {title: item.text};
            return (
                <TouchableOpacity
                    key={key}
                    style={[styles.items3,styles.itemCenter,center]}
                    onPress={()=>{Main.goRouter(this,item.label,params)}}
                >
                    {this._renderText(item.text, item.label)}
                </TouchableOpacity>
            );
        }.bind(this));
    },

    render: function () {
        return (
            <View style={[styles.footer,styles.bgColor]}>

                {this._renderItem()}
            </View>
        );
    }
});


/**
 * 全局layout
 * 用法  : <Layout content={content}/>
 * @param  content 中间内容
 */

const Layout = React.createClass({
    componentDidMount: function () {

    },
    render: function () {

        return (
            <View style={styles.container}>
                <Header />

                <View style={[styles.content]}>
                    <ListBox/>
                </View>
                <Footer />

            </View>
        );
    }
});


/**
 * loading 按钮
 * 用法  : <Loading size={40}/>
 * @param  size - 按钮的大小
 */

const Loading = React.createClass({

    render: function () {
        var size = this.props.size || 30;
        var color = this.props.color || '#000';
        return (
            <View style={[styles.itemCenter]}>
                <Icon name='load-d' size={size} color={color}
                      style={{width:size,height:size,opacity:size*0.01+0.3}}/>
                <Text style={{color:colors.default,fontSize:fontSize.small,marginBottom:10}}>{this.props.text}</Text>
            </View>
        );
    }
});
/**
 * 加载失败提示
 */
const LoadErr = React.createClass({

    render: function () {
        var size = this.props.size || 30;
        return (
            <View style={[styles.itemCenter,{marginTop:height/3}]}>
                <Icon name='eye-disabled' size={size} color='#000'
                      style={{width:size,height:size,opacity:size*0.01+0.3}}/>
                <Text style={{color:colors.default,fontSize:fontSize.h3,marginBottom:10}}>加载失败,点击重试</Text>
            </View>
        );
    }
});


/**
 * 返回按钮
 * 用法  : <BackButton size={40}/>
 * @param  size - 返回按钮的大小
 */
const BackButton = React.createClass({
    getClass: function (size) {
        var backButton = {
            width: size,
            height: size,
            backgroundColor: '#000',
            opacity: 0.5,
            borderRadius: 20,
            //top: height - size - 100,
            //left: 10,
            //position: 'absolute'
        }
        return backButton;
    },

    render: function () {
        var size = this.props.size || width / 9;
        var className = this.getClass(size);

        return (
            <View style={[className,this.props.style]}>
                <Icon
                    name='ios-arrow-left'
                    size={size}
                    color='#fff'
                    style={{width:size,height:size,left:5,backgroundColor:'transparent'}}/>
            </View>
        );

    }
});
/**
 * 用户评星
 */
const Stars = React.createClass({

    _renderStar:function() {
        var num = this.props.num || 1;
        var size = this.props.size || fontSize.default;
        var stars = [];
        for (var i = 0; i < num; i++)
        {
            stars.push(<Icon
                key={i}
                name='ios-star'
                size={size}
                style={{width:size,height:size,left:5,backgroundColor:'transparent',color:'#f0ad4e'}}/>);
        }
        return stars;
    },
    render:function(){
        return (
            <View style={{flexDirection:'row',left:-6}}>
                {this._renderStar()}
            </View>
        );
    }
});

const Web  = React.createClass({
    getInitialState: function() {
        return {
            status: 'No Page Loaded',
            backButtonEnabled: false,
            forwardButtonEnabled: false,
            loading: true,
            scalesPageToFit: true,
        };
    },
    goBack: function() {
        this.refs['webview'].goBack();
    },

    goForward: function() {
        this.refs['webview'].goForward();
    },

    reload: function() {
        this.refs['webview'].reload();
    },

    onShouldStartLoadWithRequest: function(event) {
        //console.log("==>onShouldStartLoadWithRequest",event);
        // Implement any custom loading logic here, don't forget to return!
        return true;
    },
    //
    onNavigationStateChange: function(navState) {
        //console.log("==>onNavigationStateChange",navState.url);
        var p = Main.urlParse(navState.url);
        if(p.search)
        {
            //var info =p.query.info ?  decodeURIComponent(p.query.info) : '';
            //if(info)
            //{
            //    AsyncStorage.setItem('_userinfo',info,()=>{
            //        var data = this.props;
            //        var userinfo =  JSON.parse(info);
            //        var modal = (<MModal visible={true} >
            //            <UserCenter {...data} userinfo={userinfo}></UserCenter>
            //        </MModal>);
            //        RootSiblings.show(modal);
            //    });
            //
            //}
        }


    },



    render:function(){
        return (
            <WebView
                ref={'webview'}
                source={{uri: this.props.url}}
                automaticallyAdjustContentInsets={false}
                javaScriptEnabled={true}
                domStorageEnabled={true}
                decelerationRate="normal"
                onNavigationStateChange={this.onNavigationStateChange}
                onShouldStartLoadWithRequest={this.onShouldStartLoadWithRequest}
                startInLoadingState={true}
                //scalesPageToFit={this.state.scalesPageToFit}
            />
        );
    }
})

const Style = {
    Header: Header,
    Layout: Layout,
    Footer: Footer,
    Loading: Loading,
    LoadErr: LoadErr,
    BackButton: BackButton,
    Stars:Stars,
    Topav:Topav,
    Web:Web,
    Login:Login

}
module.exports = Style;
